﻿namespace Hidistro.SaleSystem.Shopping
{
    using Hidistro.Core;
    using Hidistro.Entities;
    using Hidistro.Entities.Commodities;
    using Hidistro.Entities.Members;
    using Hidistro.Entities.Orders;
    using Hidistro.Entities.Promotions;
    using Hidistro.Entities.Sales;
    using Hidistro.Membership.Context;
    using Hidistro.SqlDal.Commodities;
    using Hidistro.SqlDal.Members;
    using Hidistro.SqlDal.Orders;
    using Hidistro.SqlDal.Promotions;
    using Hidistro.SqlDal.Sales;
    using Microsoft.Practices.EnterpriseLibrary.Data;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.IO;
    using System.Net;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Web.Configuration;
    using wnxd.javascript;

    public static class ShoppingProcessor
    {
        public static decimal CalcFreight(int regionId, decimal totalWeight, ShippingModeInfo shippingModeInfo)
        {
            decimal price = 0M;
            int topRegionId = RegionHelper.GetTopRegionId(regionId);
            decimal num3 = totalWeight;
            int num4 = 1;
            if ((num3 > shippingModeInfo.Weight) && (shippingModeInfo.AddWeight.HasValue && (shippingModeInfo.AddWeight.Value > 0M)))
            {
                decimal num6 = num3 - shippingModeInfo.Weight;
                if ((num6 % shippingModeInfo.AddWeight) == 0M)
                {
                    num4 = Convert.ToInt32(Math.Truncate((decimal)((num3 - shippingModeInfo.Weight) / shippingModeInfo.AddWeight.Value)));
                }
                else
                {
                    num4 = Convert.ToInt32(Math.Truncate((decimal)((num3 - shippingModeInfo.Weight) / shippingModeInfo.AddWeight.Value))) + 1;
                }
            }
            if ((shippingModeInfo.ModeGroup == null) || (shippingModeInfo.ModeGroup.Count == 0))
            {
                if ((num3 > shippingModeInfo.Weight) && shippingModeInfo.AddPrice.HasValue)
                {
                    return ((num4 * shippingModeInfo.AddPrice.Value) + shippingModeInfo.Price);
                }
                return shippingModeInfo.Price;
            }
            int? nullable = null;
            foreach (ShippingModeGroupInfo info in shippingModeInfo.ModeGroup)
            {
                foreach (ShippingRegionInfo info2 in info.ModeRegions)
                {
                    if (topRegionId == info2.RegionId)
                    {
                        nullable = new int?(info2.GroupId);
                        break;
                    }
                }
                if (nullable.HasValue)
                {
                    if (num3 > shippingModeInfo.Weight)
                    {
                        price = (num4 * info.AddPrice) + info.Price;
                    }
                    else
                    {
                        price = info.Price;
                    }
                    break;
                }
            }
            if (nullable.HasValue)
            {
                return price;
            }
            if ((num3 > shippingModeInfo.Weight) && shippingModeInfo.AddPrice.HasValue)
            {
                return ((num4 * shippingModeInfo.AddPrice.Value) + shippingModeInfo.Price);
            }
            return shippingModeInfo.Price;
        }

        public static decimal CalcPayCharge(decimal cartMoney, PaymentModeInfo paymentModeInfo)
        {
            if (!paymentModeInfo.IsPercent)
            {
                return paymentModeInfo.Charge;
            }
            return (cartMoney * (paymentModeInfo.Charge / 100M));
        }

        public static OrderInfo ConvertShoppingCartToOrder(ShoppingCartInfo shoppingCart, bool isGroupBuy, bool isCountDown, bool isSignBuy)
        {
            if ((shoppingCart.LineItems.Count == 0) && (shoppingCart.LineGifts.Count == 0))
            {
                return null;
            }
            OrderInfo info = new OrderInfo
            {
                Points = shoppingCart.GetPoint(),
                ReducedPromotionId = shoppingCart.ReducedPromotionId,
                ReducedPromotionName = shoppingCart.ReducedPromotionName,
                ReducedPromotionAmount = shoppingCart.ReducedPromotionAmount,
                IsReduced = shoppingCart.IsReduced,
                SentTimesPointPromotionId = shoppingCart.SentTimesPointPromotionId,
                SentTimesPointPromotionName = shoppingCart.SentTimesPointPromotionName,
                IsSendTimesPoint = shoppingCart.IsSendTimesPoint,
                TimesPoint = shoppingCart.TimesPoint,
                FreightFreePromotionId = shoppingCart.FreightFreePromotionId,
                FreightFreePromotionName = shoppingCart.FreightFreePromotionName,
                IsFreightFree = shoppingCart.IsFreightFree
            };
            string str = string.Empty;
            if (shoppingCart.LineItems.Count > 0)
            {
                foreach (ShoppingCartItemInfo info2 in shoppingCart.LineItems)
                {
                    if (info2.IsSelect) str = str + string.Format("'{0}',", info2.SkuId);
                }
            }
            Dictionary<string, decimal> costPriceForItems = new Dictionary<string, decimal>();
            if (!string.IsNullOrEmpty(str))
            {
                str = str.Substring(0, str.Length - 1);
                costPriceForItems = new SkuDao().GetCostPriceForItems(str);
            }
            if (shoppingCart.LineItems.Count > 0)
            {
                foreach (ShoppingCartItemInfo info2 in shoppingCart.LineItems)
                {
                    if (info2.IsSelect)
                    {
                        decimal num = 0M;
                        if (costPriceForItems.ContainsKey(info2.SkuId))
                        {
                            num = costPriceForItems[info2.SkuId];
                        }
                        LineItemInfo info3 = new LineItemInfo
                        {
                            SkuId = info2.SkuId,
                            ProductId = info2.ProductId,
                            SKU = info2.SKU,
                            Quantity = info2.Quantity,
                            ShipmentQuantity = info2.ShippQuantity,
                            ItemCostPrice = num,
                            ItemListPrice = info2.MemberPrice,
                            ItemAdjustedPrice = info2.AdjustedPrice,
                            ItemDescription = info2.Name,
                            ThumbnailsUrl = info2.ThumbnailUrl40,
                            ItemWeight = info2.Weight,
                            SKUContent = info2.SkuContent,
                            PromotionId = info2.PromotionId,
                            PromotionName = info2.PromotionName
                        };
                        info.LineItems.Add(info3.SkuId, info3);
                    }
                }
            }
            info.Tax = 0.00M;
            info.InvoiceTitle = "";
            if (shoppingCart.LineGifts.Count > 0)
            {
                foreach (ShoppingCartGiftInfo info4 in shoppingCart.LineGifts)
                {
                    OrderGiftInfo item = new OrderGiftInfo
                    {
                        GiftId = info4.GiftId,
                        GiftName = info4.Name,
                        Quantity = info4.Quantity,
                        ThumbnailsUrl = info4.ThumbnailUrl40,
                        PromoteType = info4.PromoType,
                        CostPrice = info4.CostPrice
                    };
                    info.Gifts.Add(item);
                }
            }
            return info;
        }

        public static int CountDownOrderCount(int productid)
        {
            return new LineItemDao().CountDownOrderCount(productid);
        }
        public class SubmitInfo
        {
            public string Url { get; set; }
            public DateTime Time { get; set; }
            public string OrderId { get; set; }
        }
        public static bool CreatOrder(OrderInfo orderInfo, string Source = null)
        {
            if (orderInfo == null)
            {
                return false;
            }
            HttpContext @this = HttpContext.Current;
            try
            {
                string ip1 = @this.Request.UserHostAddress, ip2;
                if (@this.Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR") != null)
                {
                    ip2 = @this.Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR").ToString().Trim();
                }
                else
                {
                    ip2 = @this.Request.ServerVariables.Get("Remote_Addr").ToString().Trim();
                }
                orderInfo.Remark += Environment.NewLine + "连接ip:" + ip1 + Environment.NewLine + "显示ip:" + ip2 + Environment.NewLine;
                if(ip2.IndexOf("101.251.212.173")>0)
                {
                    //return false;
                }
            }
            catch
            {

            }
            bool flag = false;
            using (DbConnection connection = DatabaseFactory.CreateDatabase().CreateConnection())
            {
                connection.Open();
                DbTransaction dbTran = connection.BeginTransaction();
                try
                {
                    if (!new OrderDao().CreatOrder(orderInfo, dbTran, Source))
                    {
                        dbTran.Rollback();
                        return false;
                    }
                    if ((orderInfo.LineItems.Count > 0) && !new LineItemDao().AddOrderLineItems(orderInfo.OrderId, orderInfo.LineItems.Values, dbTran))
                    {
                        dbTran.Rollback();
                        return false;
                    }
                    if (orderInfo.Gifts.Count > 0)
                    {
                        OrderGiftDao dao = new OrderGiftDao();
                        foreach (OrderGiftInfo info in orderInfo.Gifts)
                        {
                            if (!dao.AddOrderGift(orderInfo.OrderId, info, 0, dbTran))
                            {
                                dbTran.Rollback();
                                return false;
                            }
                        }
                    }
                    if (!string.IsNullOrEmpty(orderInfo.CouponCode) && !new CouponDao().AddCouponUseRecord(orderInfo, dbTran))
                    {
                        dbTran.Rollback();
                        return false;
                    }
                    dbTran.Commit();
                    flag = true;
                }
                catch (Exception e)
                {
                    dbTran.Rollback();
                    StringBuilder str = new StringBuilder();
                    str.AppendLine(DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss"));
                    str.AppendLine("客户信息：");
                    string ip = "";
                    if (HttpContext.Current.Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR") != null)
                    {
                        ip = HttpContext.Current.Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR").ToString().Trim();
                    }
                    else
                    {
                        ip = HttpContext.Current.Request.ServerVariables.Get("Remote_Addr").ToString().Trim();
                    }
                    str.AppendLine("连接IP:" + HttpContext.Current.Request.UserHostAddress);
                    str.AppendLine("IP:" + ip);
                    str.AppendLine("连接主机名:" + HttpContext.Current.Request.UserHostName);
                    str.AppendLine("浏览器:" + HttpContext.Current.Request.Browser.Browser);
                    str.AppendLine("浏览器版本:" + HttpContext.Current.Request.Browser.MajorVersion.ToString());
                    str.AppendLine("操作系统:" + HttpContext.Current.Request.Browser.Platform);
                    str.AppendLine("错误信息:");
                    str.AppendLine("页面：" + HttpContext.Current.Request.Url.ToString());
                    str.AppendLine("错误信息：" + e.Message);
                    str.AppendLine("错误源：" + e.Source);
                    str.AppendLine("异常方法：" + e.TargetSite);
                    str.AppendLine("堆栈信息：" + e.StackTrace);
                    str.AppendLine("--------------------------------------------------------------------------------------------------");
                    string upLoadPath = WebConfigurationManager.AppSettings["LogPath"];
                    if (!Directory.Exists(upLoadPath))
                    {
                        Directory.CreateDirectory(upLoadPath);
                    }
                    string FileName;
                    string[] flist = Directory.GetFiles(upLoadPath, DateTime.Now.ToString("yyyy.MM.dd") + "_?.log");
                    if (flist != null && flist.Length > 0)
                    {
                        FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + flist.Length.ToString() + ".log";
                        FileInfo fileInfo = new FileInfo(FileName);
                        if (fileInfo != null && fileInfo.Length >= 100 * 1024 * 1024)
                        {
                            FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + (flist.Length + 1).ToString() + ".log";
                        }
                    }
                    else
                    {
                        FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_1.log";
                    }
                    File.AppendAllText(FileName, str.ToString(), Encoding.UTF8);
                    return false;
                }
                finally
                {
                    connection.Close();
                }
            }
            return flag;
        }
        private static string GetHtml(string url, int timeout = 0)
        {
            WebRequest Request = WebRequest.Create(url);
            if (timeout > 0) Request.Timeout = timeout;
            WebResponse Response = Request.GetResponse();
            Stream resStream = Response.GetResponseStream();
            StreamReader sr = new StreamReader(resStream, Encoding.UTF8);
            StringBuilder sb = new StringBuilder();
            string rl;
            while ((rl = sr.ReadLine()) != null)
            {
                sb.Append(rl);
            }
            return sb.ToString();
        }
        public static bool CutNeedPoint(int needPoint, string orderId)
        {
            Member user = HiContext.Current.User as Member;
            PointDetailInfo point = new PointDetailInfo
            {
                OrderId = orderId,
                UserId = user.UserId,
                TradeDate = DateTime.Now,
                TradeType = PointTradeType.Change,
                Reduced = new int?(needPoint),
                Points = user.Points - needPoint
            };
            if ((point.Points > 0x7fffffff) || (point.Points < 0))
            {
                point.Points = 0;
            }
            if (new PointDetailDao().AddPointDetail(point))
            {
                Users.ClearUserCache(user);
                return true;
            }
            return false;
        }

        public static DataTable GetCoupon(decimal orderAmount)
        {
            return new CouponDao().GetCoupon(orderAmount);
        }

        public static CouponInfo GetCoupon(string couponCode)
        {
            return new CouponDao().GetCoupon(couponCode);
        }

        public static IList<string> GetExpressCompanysByMode(int modeId)
        {
            return new ShippingModeDao().GetExpressCompanysByMode(modeId);
        }

        public static OrderInfo GetOrderInfo(string orderId)
        {
            return new OrderDao().GetOrderInfo(orderId);
        }

        public static PaymentModeInfo GetPaymentMode(int modeId)
        {
            return new PaymentModeDao().GetPaymentMode(modeId);
        }

        public static PaymentModeInfo GetPaymentMode(string gateway)
        {
            return new PaymentModeDao().GetPaymentMode(gateway);
        }

        public static IList<PaymentModeInfo> GetPaymentModes(PayApplicationType payApplicationType)
        {
            return new PaymentModeDao().GetPaymentModes(payApplicationType);
        }

        public static SKUItem GetProductAndSku(int productId, string options)
        {
            return new SkuDao().GetProductAndSku(HiContext.Current.User as Member, productId, options);
        }

        public static DataTable GetProductInfoBySku(string skuId)
        {
            return new SkuDao().GetProductInfoBySku(skuId);
        }

        public static ShippingModeInfo GetShippingMode(int modeId, bool includeDetail)
        {
            return new ShippingModeDao().GetShippingMode(modeId, includeDetail);
        }

        public static IList<ShippingModeInfo> GetShippingModes()
        {
            return new ShippingModeDao().GetShippingModes();
        }

        public static IList<string> GetSkuIdsBysku(string sku)
        {
            return new SkuDao().GetSkuIdsBysku(sku);
        }

        public static DataTable GetUnUpUnUpsellingSkus(int productId, int attributeId, int valueId)
        {
            return new SkuDao().GetUnUpUnUpsellingSkus(productId, attributeId, valueId);
        }

        public static DataTable GetYetShipOrders(int days)
        {
            return new OrderDao().GetYetShipOrders(days);
        }

        public static DataTable UseCoupon(decimal orderAmount)
        {
            return GetCoupon(orderAmount);
        }

        public static CouponInfo UseCoupon(decimal orderAmount, string claimCode)
        {
            if (!string.IsNullOrEmpty(claimCode))
            {
                CouponInfo coupon = GetCoupon(claimCode);
                if (coupon != null)
                {
                    decimal? amount;
                    if (coupon.Amount.HasValue)
                    {
                        amount = coupon.Amount;
                        if (!((amount.GetValueOrDefault() > 0M) && amount.HasValue) || (orderAmount < coupon.Amount.Value))
                        {
                        }
                    }
                    if (!(coupon.Amount.HasValue && (!(((amount = coupon.Amount).GetValueOrDefault() == 0M) && amount.HasValue) || (orderAmount <= coupon.DiscountValue))))
                    {
                        return coupon;
                    }
                }
            }
            return null;
        }
    }
}

